using System;

namespace Magiq.Support {
    public class Reference<T> where T : class {
        private readonly WeakReference weakReference;
        private T target;

        public Reference(T target) {
            if (target == null)
                throw new ArgumentNullException("target");

            this.target = target;
            weakReference = new WeakReference(target);
        }

        public bool IsStrong {
            get { return !IsWeak; }
        }

        public int TimesUsed { get; private set; }

        public T Target {
            get {
                var t = weakReference.Target;
                if (t != null) {
                    TimesUsed++;
                    MakeStrong();
                    return (T) weakReference.Target;
                }

                return null;
            }
        }

        public bool IsAlive {
            get { return weakReference.IsAlive; }
        }

        public bool IsWeak { get; private set; }

        public void MakeWeak() {
            target = null;
            IsWeak = true;
        }

        public void MakeStrong() {
            target = (T) weakReference.Target;
            IsWeak = false;
        }
    }
}